import {Component, Input, Output, EventEmitter} from '@angular/core';
import {
    AlertController,
    IonicPage,
    NavController,
    NavParams,
    ToastController,
    Platform,
    ItemSliding
} from 'ionic-angular';

import {ClientNoteListProvider} from '../../../../../providers/client/client-note/client-note-list/client-note-list.provider';
import {FileService} from '../../../../../services/native/file/file.service';
import {RecorderService} from "../../../../../services/recorder.service";
import {FileTransfer, FileUploadOptions, FileTransferObject} from '@ionic-native/file-transfer';
import {ClientNoteEditProvider} from "../../../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {PermissionsService} from "../../../../../services/native/permissions/permissions.service";
import {LocalStorageService} from "../../../../../services/native/local-storage/local-storage.service";
import {SideMenuService} from "../../../../../services/common/side-menu.service";
import {ToastService} from '../../../../../services/common/toast.service';

@Component({
    selector: 'client-detail-progress',
    templateUrl: 'client-detail-progress.component.html',
    providers: [
        FileTransfer,
        ClientNoteListProvider,
        ClientNoteEditProvider,
        RecorderService,
        FileService,
        LocalStorageService,
        PermissionsService,
        SideMenuService,
        ToastService
    ]
})
export class ClientDetailProgressComponent {
    // 获取跟进请求对象
    @Input() resquestItem: any;
    // 到跟进详情事件
    @Output() detail: EventEmitter<any> = new EventEmitter();
    // 跟进列表
    @Input() progressList: any[] = [];
    // 模块title
    @Input() title: string;
    // 是否进入页面
    @Input() pageStatus: any;
    // 跟进人员类型
    @Input() typeNum:number;
    // 数据请求成功
    @Input() requestSuccess:boolean;

    // 当前播放语音id
    private voiceId: string;
    // 标记当前下载语音笔记的ID
    private currentVoiceId: any;
    // 语音播放停止切换
    private switchPlayOrStop: boolean = true;
    // 语音播放计时
    private playTimerLength: number = null;
    // 语音播放计时器
    private playerVoiceTimer: any;
    // 云端语音资源下载时间计时
    private downloadTimerLength: number = 0;
    // 云端语音资源下载时间计时器
    private voiceDownloadTimer: any;
    // 数据输入变化
    private dataChange:boolean=true;

    constructor(public clientNoteListProvider: ClientNoteListProvider,
                private platform: Platform,
                private fileService: FileService,
                private recorderService: RecorderService,
                private toastService:ToastService
                ) {
        this.platform.pause.subscribe(()=>{
            this.stopVoice();
            this.switchPlayOrStop = true;
            console.log('app exit')
        })
    }

    ngOnInit() {
        /*if(this.resquestItem.clientId||this.resquestItem){
            this.getProgressList();
        }*/
    }

    ngOnDestroy() {
        this.stopVoice();
    }

    ngOnChanges() {
        if(this.progressList.length){
            this.dataChange=true;
        }else{
            this.dataChange=false;
        }
        this.stopVoice();
    }

    // 获取跟进数据
    getProgressList() {
        console.log(this.resquestItem);
        this.clientNoteListProvider.getProgressList(this.resquestItem).subscribe((res) => {
            this.progressList = res['notes']
        })
    }

    // 获取笔记类型标记
    getNoteType(item: any) {
        const types = ['[销售]', '[增员]', '[其他]', '[系统]'];
        return types[item.noteType - 1]
    }

    // 播放或停止录音
    playOrStop(e, name, id, length) {
        e.stopPropagation();
        e.preventDefault();
        if (!this.platform.is('cordova')) {
            return;
        }
        if (!this.switchPlayOrStop) {
            this.stopVoice();
            if (this.currentVoiceId == id) {
                this.switchPlayOrStop = true;
                return false;
            }
        } else {
            this.switchPlayOrStop = false;
        }
        this.currentVoiceId = id;
        this.playTimerLength = null;
        this.voiceId = null;
        // 清除下载语音计时器
        if (this.voiceDownloadTimer) {
            clearInterval(this.voiceDownloadTimer)
        }
        this.downloadTimerLength = 0;
        this.calcDownloadTimer();
        // 下载语音
        this.fileService.getFile(name, name).subscribe((res) => {
            this.recorderService.releasePlay();
            this.recorderService.startPlay(this.recorderService.getPlatformFileUrl(res.fileUrl));
            // 清除下载语音计时器
            clearInterval(this.voiceDownloadTimer);
            this.downloadTimerLength = 0;
            // 播放计时器切换
            this.playTimerLength = length;
            this.voiceId = id;
            if (this.playerVoiceTimer) {
                clearInterval(this.playerVoiceTimer);
            }
            this.calcTimer();
        }, error => {
            this.toastService.showToast('语音下载失败');
            clearInterval(this.voiceDownloadTimer);
            console.log(error);
        });
    }

    // 下载计时器
    calcDownloadTimer() {
        this.downloadTimerLength = 0;
        this.voiceDownloadTimer = setInterval(() => {
            this.downloadTimerLength++;
        }, 1000)
    }

    // 播放计时器
    calcTimer() {
        this.playerVoiceTimer = setInterval(() => {
            this.playTimerLength--;
            if (this.playTimerLength <= 0) {
                if (!this.switchPlayOrStop) {
                    this.switchPlayOrStop = true;
                }
                clearInterval(this.playerVoiceTimer);
                this.playTimerLength = null;
                this.voiceId = null;
            }
        }, 1000)
    }

    // 停止播放音频
    stopVoice() {
        clearInterval(this.playerVoiceTimer);
        this.recorderService.stopPlay();
        this.recorderService.pausePlay();
        this.recorderService.releasePlay();
        this.voiceId = null;
    }

    // 到跟进列表
    goToProgressList() {
        this.detail.emit(100);
    }

}
